<template>
  <view class="profile-edit-page">
    <!-- 表单区域 -->
    <view class="form-container">
      <!-- 头像 -->
      <view class="form-item" @click="handleAvatarUpload">
        <text class="label">头像</text>
        <view class="value-area">
          <image class="avatar-preview" :src="formData.avatarUrl || '/static/default_avatar.png'" mode="aspectFill">
          </image>
          <u-icon name="arrow-right" size="20" color="#999"></u-icon>
        </view>
      </view>

      <!-- 昵称 -->
      <view class="form-item">
        <text class="label">昵称</text>
        <view class="value-area">
          <!-- 使用 type="nickname" 可以在键盘上方显示微信昵称 -->
          <input class="input" type="nickname" v-model="formData.nickname" placeholder="请输入昵称" maxlength="20" />
        </view>
      </view>

      <!-- 手机号 -->
      <view class="form-item">
        <text class="label">手机号</text>
        <view class="value-area">
          <input class="input" v-model="formData.phone" placeholder="请输入手机号" type="number" maxlength="11" />
        </view>
      </view>

      <!-- 性别 -->
      <view class="form-item" @click="showGenderPicker = true">
        <text class="label">性别</text>
        <view class="value-area">
          <text class="value-text" :class="{ 'placeholder': !formData.gender }">
            {{ formData.gender == 1 ? '男' : formData.gender == 2 ? '女' : '' || '请选择性别' }}
          </text>
          <u-icon name="arrow-right" size="20" color="#999"></u-icon>
        </view>
      </view>

      <!-- 国家 -->
      <view class="form-item">
        <text class="label">国家</text>
        <view class="value-area">
          <input class="input" v-model="formData.country" placeholder="请输入国家" maxlength="30" />
        </view>
      </view>

      <!-- 省份 -->
      <view class="form-item">
        <text class="label">省份</text>
        <view class="value-area">
          <input class="input" v-model="formData.province" placeholder="请输入省份" maxlength="30" />
        </view>
      </view>

      <!-- 城市 -->
      <view class="form-item">
        <text class="label">城市</text>
        <view class="value-area">
          <input class="input" v-model="formData.city" placeholder="请输入城市" maxlength="30" />
        </view>
      </view>
    </view>

    <!-- 保存按钮 -->
    <view class="save-button-area">
      <button class="save-button" @click="handleSave" type="primary">保存</button>
    </view>

    <!-- 选择器弹窗容器 -->
    <view class="picker-container">
      <!-- 性别选择器 -->
      <u-picker :show="showGenderPicker" :columns="genderColumns" keyName="text" @confirm="handleGenderConfirm"
        @cancel="showGenderPicker = false" @close="showGenderPicker = false" :closeOnClickOverlay="true"></u-picker>
    </view>
  </view>
</template>

<script>
import { request, BASE_URL } from '@/utils/request';


export default {
  data() {
    return {
      // 表单数据
      formData: {
        id: '',
        avatarUrl: '',
        nickname: '',
        phone: '',
        gender: '',
        country: '',
        province: '',
        city: ''
      },

      // 选择器显示状态
      showGenderPicker: false,

      // 选择器数据
      genderColumns: [['男', '女', '未知']]
    };
  },

  onLoad(props) {
    // 加载用户信息
    if (props.id) {
      this.formData.id = props.id;
    }
    this.loadUserInfo();
  },

  methods: {
    // 加载用户信息
    loadUserInfo() {
      const userInfo = uni.getStorageSync('userInfo');
      if (userInfo) {
        this.formData = {
          id: userInfo.id,
          avatarUrl: userInfo.avatarUrl || userInfo.avatar || '',
          nickname: userInfo.nickname || '',
          phone: userInfo.phone || '',
          gender: userInfo.gender || '',
          country: userInfo.country || '中国',
          province: userInfo.province || '',
          city: userInfo.city || ''
        };

        // 如果已选择省份，加载对应城市
        if (this.formData.province) {
          this.loadCities(this.formData.province);
        }
      }
    },

    // 加载省份数据
    loadProvinces() {
      // 中国主要省份列表
      const provinces = [
        '北京市', '上海市', '天津市', '重庆市',
        '河北省', '山西省', '辽宁省', '吉林省', '黑龙江省',
        '江苏省', '浙江省', '安徽省', '福建省', '江西省', '山东省',
        '河南省', '湖北省', '湖南省', '广东省', '海南省',
        '四川省', '贵州省', '云南省', '陕西省', '甘肃省', '青海省',
        '广西壮族自治区', '内蒙古自治区', '西藏自治区', '宁夏回族自治区', '新疆维吾尔自治区',
        '香港特别行政区', '澳门特别行政区', '台湾省'
      ];
      this.provinceColumns = [provinces];
    },

    // 加载城市数据
    loadCities(province) {
      // 简化的城市数据，实际项目中应该从后端获取
      const cityMap = {
        '北京市': ['东城区', '西城区', '朝阳区', '海淀区', '丰台区', '石景山区', '通州区', '顺义区'],
        '上海市': ['黄浦区', '徐汇区', '长宁区', '静安区', '普陀区', '虹口区', '杨浦区', '浦东新区'],
        '广东省': ['广州市', '深圳市', '珠海市', '东莞市', '佛山市', '中山市', '惠州市', '江门市'],
        '江苏省': ['南京市', '苏州市', '无锡市', '常州市', '南通市', '扬州市', '镇江市', '泰州市'],
        '浙江省': ['杭州市', '宁波市', '温州市', '嘉兴市', '湖州市', '绍兴市', '金华市', '台州市'],
        '山东省': ['济南市', '青岛市', '烟台市', '潍坊市', '济宁市', '淄博市', '临沂市', '威海市'],
        '河南省': ['郑州市', '洛阳市', '开封市', '南阳市', '安阳市', '新乡市', '平顶山市', '许昌市'],
        '湖北省': ['武汉市', '襄阳市', '宜昌市', '黄石市', '荆州市', '十堰市', '孝感市', '黄冈市'],
        '湖南省': ['长沙市', '株洲市', '湘潭市', '衡阳市', '岳阳市', '常德市', '张家界市', '益阳市'],
        '四川省': ['成都市', '绵阳市', '德阳市', '南充市', '宜宾市', '自贡市', '泸州市', '达州市']
      };

      this.cityColumns = [cityMap[province] || ['请先选择省份']];
    },

    //处理头像上传
    handleAvatarUpload() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const tempFilePath = res.tempFilePaths[0];
          this.uploadAvatar(tempFilePath);
        }
      });
    },

    // 上传头像到服务器
    async uploadAvatar(filePath) {
      try {
        uni.showLoading({ title: '上传中...' });
        const userStore = uni.getStorageSync('userInfo');
        const accessToken = uni.getStorageSync('accessToken');

        const uploadRes = await uni.uploadFile({
          url: `https://abc.qctrips.cn/local-file/upload`,
          filePath: filePath,
          name: 'file',
          header: {
            'Authorization': accessToken
          }
        });
        uni.hideLoading();
        if (uploadRes.statusCode === 200) {
          const result = JSON.parse(uploadRes.data);
          if (result.code === 200) {
            this.formData.avatarUrl = result.data.url;
            uni.showToast({ title: '上传成功', icon: 'success' });
          } else {
            uni.showToast({ title: result.message || '上传失败', icon: 'none' });
          }
        } else {
          uni.showToast({ title: '上传失败', icon: 'none' });
        }
      } catch (error) {
        uni.hideLoading();
        console.error('上传头像失败:', error);
        uni.showToast({ title: '上传失败', icon: 'none' });
      }
    },

    // 性别选择确认
    handleGenderConfirm(e) {
      const value = e.value[0];
      if (value === '男') {
        this.formData.gender = 1;
      }
      else if (value === '女') {
        this.formData.gender = 2;
      }
      else {
        this.formData.gender = 0;
      }
      this.showGenderPicker = false;
    },

    // 国家选择确认
    handleCountryConfirm(e) {
      this.formData.country = e.value[0];
      this.showCountryPicker = false;
    },

    // 省份选择确认
    handleProvinceConfirm(e) {
      this.formData.province = e.value[0];
      this.formData.city = ''; // 清空城市
      this.loadCities(e.value[0]); // 加载新的城市列表
      this.showProvincePicker = false;
    },

    // 城市选择确认
    handleCityConfirm(e) {
      this.formData.city = e.value[0];
      this.showCityPicker = false;
    },

    // 保存信息
    async handleSave() {
      // 验证表单
      if (!this.formData.nickname) {
        uni.showToast({ title: '请输入昵称', icon: 'none' });
        return;
      }

      if (this.formData.phone && !/^1[3-9]\d{9}$/.test(this.formData.phone)) {
        uni.showToast({ title: '请输入正确的手机号', icon: 'none' });
        return;
      }

      try {
        uni.showLoading({ title: '保存中...' });

        // 调用更新接口
        const result = await request({
          url: `${BASE_URL}/wechat-user/put`,
          method: 'PUT',
          data: this.formData
        });

        uni.hideLoading();

        if (result.code === 200) {
          // 更新本地存储
          const userInfo = uni.getStorageSync('userInfo') || {};
          const updatedUserInfo = {
            ...userInfo,
            nickname: this.formData.nickname,
            avatarUrl: this.formData.avatarUrl,
            avatar: this.formData.avatarUrl,
            phone: this.formData.phone,
            gender: this.formData.gender,
            country: this.formData.country,
            province: this.formData.province,
            city: this.formData.city
          };
          uni.setStorageSync('userInfo', updatedUserInfo);

          uni.showToast({ title: '保存成功', icon: 'success' });

          // 延迟返回上一页
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          uni.showToast({ title: result.message || '保存失败', icon: 'none' });
        }
      } catch (error) {
        uni.hideLoading();
        console.error('保存失败:', error);
        uni.showToast({ title: '保存失败，请重试', icon: 'none' });
      }
    },

    // 返回上一页
    handleBack() {
      uni.navigateBack();
    }
  }
};
</script>

<style lang="scss" scoped>
.profile-edit-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 自定义导航栏 */
.custom-navbar {
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

.navbar-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 88rpx;
  padding: 0 24rpx;
}

.back-btn {
  width: 80rpx;
  height: 88rpx;
  display: flex;
  align-items: center;
}

.navbar-title {
  flex: 1;
  text-align: center;
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.save-btn {
  width: 80rpx;
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.save-text {
  font-size: 32rpx;
  color: #007AFF;
}

/* 表单容器 */
.form-container {
  margin-top: 24rpx;
  background-color: #fff;
}

/* 表单项 */
.form-item {
  display: flex;
  align-items: center;
  padding: 32rpx 24rpx;
  border-bottom: 1rpx solid #f0f0f0;

  &:last-child {
    border-bottom: none;
  }
}

.label {
  width: 160rpx;
  font-size: 30rpx;
  color: #333;
  font-weight: 500;
}

.value-area {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.input {
  flex: 1;
  font-size: 30rpx;
  color: #333;
  text-align: right;
}

.value-text {
  font-size: 30rpx;
  color: #333;
  margin-right: 16rpx;

  &.placeholder {
    color: #999;
  }
}

/* 头像预览 */
.avatar-preview {
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  margin-right: 16rpx;
}

/* 保存按钮区域 */
.save-button-area {
  padding: 48rpx 24rpx;
  padding-bottom: calc(48rpx + env(safe-area-inset-bottom));
}

.save-button {
  width: 600rpx;
  height: 88rpx;
  background: linear-gradient(135deg, #ff6700 0%, #ff6700 100%);
  border-radius: 44rpx;
  font-size: 32rpx;
  font-weight: bold;
  color: #fff;
  border: none;
  box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.4);
  transition: all 0.3s ease;

  &::after {
    border: none;
  }

  &:active {
    transform: scale(0.98);
    box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
  }
}

/* 选择器容器 */
.picker-container {
  position: relative;
  z-index: 9999;
}
</style>